package com.ljw.punishment.rulefactory;

import com.ljw.punishment.baserule.CommonRule;
import com.ljw.punishment.customBiDuifunction.CustomFunction;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.support.AbstractRuleFactory;
import org.jeasy.rules.support.RuleDefinition;
import org.jeasy.rules.support.reader.JsonRuleDefinitionReader;
import org.jeasy.rules.support.reader.RuleDefinitionReader;
import org.mvel2.ParserContext;
import org.springframework.context.annotation.Bean;

import java.io.Reader;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author lijunwei
 * @date 2025/5/21
 */
public class CustomRuleFactory extends AbstractRuleFactory {

    private final RuleDefinitionReader reader;
    private final ParserContext parserContext;

    public CustomRuleFactory(RuleDefinitionReader reader, ParserContext parserContext) {
        this.reader = reader;
        this.parserContext = parserContext;
    }

    public CustomRuleFactory(RuleDefinitionReader reader) {
        this(reader, new ParserContext());
    }

    public Rule createRule(Reader ruleDescriptor) throws Exception {
        List<RuleDefinition> ruleDefinitions = reader.read(ruleDescriptor);
        if (ruleDefinitions.isEmpty()) {
            throw new Exception("规则元信息读取失败");
        }
        return createRule(ruleDefinitions.get(0));
    }

    @Override
    protected Rule createSimpleRule(RuleDefinition ruleDefinition) {
        CommonRule commonRule = new CommonRule(ruleDefinition.getName(), ruleDefinition.getDescription(),
                ruleDefinition.getPriority());
        commonRule.when(ruleDefinition.getCondition());
        for (String action : ruleDefinition.getActions()) {
            commonRule.then(action);
        }
        return commonRule;
    }


    /**
     * json 格式读取规则元信息
     *
     * @return
     */

    public static JsonRuleDefinitionReader createJSONReader() {
        return new JsonRuleDefinitionReader();
    }

    public static ParserContext initParseContext() {
        ParserContext ctx = new ParserContext();

        Method[] declaredMethods = CustomFunction.class.getDeclaredMethods();

        for (Method declaredMethod : declaredMethods) {
            ctx.addImport(declaredMethod.getName(), declaredMethod);
        }
        return ctx;
    }

}
